/**
 * 房源信息
 */
define(function (require, exports, module) {
    'use strict';
    var angular = require('angular');
    var util = require('util');
    var ui = require('ui');
    require('jqtree');
    require('pagination');
    var _ = require('underscore');

    var api_prefix = G_CONFIG['api_prefix']+'ydxs/s-room/';

    var indexData = {};

    angular.module('sourcesInfo',[])
        .factory('sourcesInfoService',['$rootScope','$compile','$http',function($rootScope,$compile,$http){
            return {
                getRoomTree: function (proj_id,scope) {
                    var url = api_prefix + 'get-room-tree';
                    var data = {
                        proj_id: proj_id,
                        NEED_TOKEN : false
                    };

                    $http.get(url, {params:data}).then(function (res) {
                        if (res.data.retCode == 0) {
                            scope.roomTreeData = res.data.data || []; //列表

                            indexData = {};// reset indexData

                            /**
                             * 转换数据
                             * @param roomTreeData
                             * @returns {*|U[]|any}
                             */
                            var transferData = function (roomTreeData) {
                                return $.map(roomTreeData || [], function (item) {
                                    item.id = item.s_buildingId;
                                    item.parentId = item.TreeParentGUID;
                                    item.name = item.bld_name;

                                    //平铺树数据
                                    indexData[item.s_buildingId] = item;

                                    var children = item.children;
                                    if (children && children.length > 0) {
                                        transferData(children);
                                    }
                                    return item;
                                });
                            };

                            var wrapData = transferData(scope.roomTreeData);
                            var $tree = $('#tree_table');
                            $tree.tree('loadData', wrapData);

                            $compile($tree)(scope);

                            if(wrapData.length > 0 ){
                                scope.query.s_buildingId = wrapData[0].s_buildingId;
                                scope.search();
                            }

                            $('#tree_table').tree({data: scope.roomTreeData});
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    }).finally(function(){
                        scope.loading = false;
                    });

                },
                searchRoom : function(proj_id,scope){
                    var url = api_prefix + "get-room-list";
                    var data = {
                        proj_id: proj_id,
                        s_buildingId : scope.query.s_buildingId,
                        room : scope.query.room,
                        roomStatus : scope.query.roomStatus,
                        pageIndex : scope.query.pageIndex,
                        pageSize : scope.query.pageSize,
                        NEED_TOKEN : false
                    };
                    $http.get(url, {params:data}).then(function (res) {
                        if (res.data.retCode == 0) {
                            var data = res.data.data;
                            scope.rooms = data.data || []; //列表
                            scope.query.total = data.total;
                            scope.statistics = {
                                ws : data.ws,
                                wfp : data.wfp,
                                yxk : data.yxk,
                                ys : data.ys,
                                'ws-pec' : data['ws-pec'],
                                'wfp-pec' : data['wfp-pec'],
                                'yxk-pec' : data['yxk-pec'],
                                'ys-pec' : data['ys-pec']
                            };
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    }).finally(function(){
                        scope.loading = false;
                    });
                },
                getCheckRoomIds : function(scope){
                    var filterData = _.filter(scope.rooms,function(obj){return obj.checked ===true});
                    return _.pluck(filterData,'s_roomId').join(',');
                },
                changeStatus : function(rooms,status,scope){
                    var url = api_prefix + "batch-change-status";
                    var data = {
                        roomIds : this.getCheckRoomIds(scope),
                        roomStatus : status,
                        NEED_TOKEN : false
                    };
                    $http.post(url,data).then(function (res) {
                        if (res.data.retCode == 0) {
                            ui.showSucTip("更新状态成功！");
                            scope.checkedRooms = false;
                            scope.search();
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    });
                },
                deleteRooms : function(scope){
                    var url = api_prefix + "batch-del-room";
                    var data = {
                        roomIds : this.getCheckRoomIds(scope),
                        NEED_TOKEN : false
                    };
                    $http.post(url,data).then(function (res) {
                        if (res.data.retCode == 0) {
                            ui.showSucTip("删除成功！");
                            scope.checkedRooms = false;
                            var len = data.roomIds ? data.roomIds.split(',').length : 0;
                            scope.query.pageIndex = util.calDeletedPage(scope.query.total,scope.query.pageIndex,scope.query.pageSize,len);
                            scope.search();
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    });
                },
                delBuilding : function(s_buildingId,scope){
                    var _this = this;
                    var url = api_prefix + 'delete-build';
                    $http.post(url,{sbuildingId : s_buildingId,NEED_TOKEN : false,custom_error : true}).then(function (res) {
                        ui.showSucTip('删除成功！');
                        _this.getRoomTree($rootScope.curProjectId,scope);
                    },function(res){
                        ui.showErrTip(res.data.errMsg);
                    });
                },
                writeBuild : function(data,scope,$dialog){
                    var _this = this;
                    var url = api_prefix + "write-build";
                    data.NEED_TOKEN = false;
                    $http.post(url, data).then(function (res) {
                        if (res.data.retCode == 0) {
                            _this.getRoomTree($rootScope.curProjectId,scope);
                            $dialog.close();
                            ui.showSucTip("操作成功！");
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    });
                },
                writeRoom : function(data,scope){
                    var url = api_prefix + "write-room";
                    data.NEED_TOKEN = false
                    $http.post(url,data).then(function (res) {
                        if (res.data.retCode == 0) {
                            ui.showSucTip("更新房间成功！");
                            scope.search();
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    });
                },
                checkBindErp : function(scope){
                    var url = api_prefix + 'check-bind-erp';
                    var data = {
                        proj_id : $rootScope.curProjectId,
                        NEED_TOKEN : false
                    };
                    $http.get(url, {params:data}).then(function (res) {
                        if (res.data.retCode == 0) {
                            scope.bindErp = res.data.data;
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    });
                },
                hasBindZtc : function(scope){
                    var url = G_CONFIG['api_prefix']+'common/my-applicationto-project/has-project-app';
                    var data = {
                        proj_id : $rootScope.curProjectId,
                        app_code : 5020,
                        NEED_TOKEN : false
                    };
                    $http.get(url, {params:data}).then(function (res) {
                        if (res.data.retCode == 0) {
                            scope.bindZtc = res.data.data;
                        } else {
                            ui.showErrTip(res.data.errMsg);
                        }
                    });
                }
            };
        }])
        .controller('sourcesInfoCtl',['$timeout','$rootScope','$scope','manageService','sourcesInfoService',
            function($timeout,$rootScope,$scope,manageService,sourcesInfoService){
                $scope.loading = true;

                //是否有房源修改权限
                manageService.hasFuncCodePermission('0000200104','02').then(function(bol){
                    $scope.permissionRoomUpdate = bol;
                });

                //路由切换时
                function sourcesInit() {
                    //初始化时
                    sourcesInfoService.getRoomTree($rootScope.curProjectId, $scope);
                    sourcesInfoService.checkBindErp($scope);
                    sourcesInfoService.hasBindZtc($scope);
                }

                // 查询条件初始化
                function queryReset(){
                    $scope.query.room = '';
                    $scope.query.pageIndex = 1;
                }

                if($rootScope.curProjectId){
                    sourcesInit();
                }

                //切换项目id时
                $scope.$on('changeCurProjectId',function(event,curProjectId){
                    sourcesInit();
                    $scope.isExpand = false;
                    queryReset();
                });

                //房间查询参数
                $scope.query = {
                    s_buildingId : '',
                    room : '',
                    roomStatus : '',
                    pageIndex : 1,
                    pageSize : 10,
                    total : 0
                };

                $scope.roomStatusList = [{text: '未放盘', value: '1'}, {text: '未售', value: '2'}, {
                                            text: '已售',
                                            value: '3'
                                        }, {text: '预销控', value: '4'}];

                //房间被选中时
                $scope.$watch('checkedRooms',function(nVal,oVal){
                    if(nVal===undefined){return;}
                    if(nVal===true){
                        $.each($scope.rooms,function(){
                            this.checked = true;
                        });
                    }else{
                        $.each($scope.rooms,function(){
                            this.checked = false;
                        });
                    }
                });

                //change room status
                $scope.changeQueryRoomStatus = function(status){
                    $scope.query.roomStatus = status;
                    $scope.query.pageIndex = 1;//reset pageIndex
                    $scope.search();
                };



                $scope.treeExpand = function(){
                    var treeRoot = $('#tree_table').tree('getTree');
                    _.each(treeRoot.children || [],function(node){
                        $('#tree_table').tree('toggle',node);
                    });
                    $scope.isExpand = !$scope.isExpand;
                };

                //模糊查询房间
                $scope.fuzzySearch = function(){
                    $scope.query.pageIndex = 1;
                    $scope.search();
                };

                //查询房间
                $scope.search = function(){
                    sourcesInfoService.searchRoom($rootScope.curProjectId,$scope);
                };

                //分页切换
                $scope.changedPage = function(pageIndex){
                    $scope.query.pageIndex = pageIndex;
                    $scope.search();
                };

                //新增区域
                $scope.addArea = function(id,$data,$dialog){
                    sourcesInfoService.writeBuild({
                            sbuildingId : indexData[id].s_buildingId,
                            bld_name : $data.name,
                            isbld : '0',
                            token : util.getToken(),
                            c_sbuildingId : ''
                        },$scope,$dialog);
                    return false;
                };

                //新增楼栋
                $scope.addLoudong = function(id,$data,$dialog){
                    var node = indexData[id];
                    sourcesInfoService.writeBuild({
                            sbuildingId : node.s_buildingId,
                            bld_name : $data.name,
                            isbld : '1',
                            token : util.getToken(),
                            c_sbuildingId : ''
                        },$scope,$dialog);
                    return false;
                };

                //编辑区域楼栋
                $scope.editAreaLoudong = function(name,title,$data){
                    $data.name = name;
                    $data.title = title;
                };

                $scope.addAreaLoudong = function(title,$data){
                    $data.title = title;
                };

                //更新区域楼栋
                $scope.updateAreaLoudong = function(id, $data,$dialog){
                    var node = indexData[id];
                    if(node.bld_name !== $data.name){
                        sourcesInfoService.writeBuild({
                            sbuildingId : node.TreeParentGUID,
                            bld_name : $data.name,
                            isbld : node.isbld,
                            token : util.getToken(),
                            c_sbuildingId : node.s_buildingId
                        },$scope,$dialog);
                    }else{
                        util.alert('请先修改名称再保存！');
                    }
                    return false;
                };

                $scope.setInitRoomStatus = function($data){
                    if($scope.hasBindErp()){
                        return false;
                    }
                    if($scope.hasCheckedRoom()){
                        $data.roomStatusList = $scope.roomStatusList;
                        $data.status = '1';
                    }else{
                        util.notify('请先选择房间！');
                        return false;
                    }
                };

                //批量更新房间状态
                $scope.changeRoomStatus = function($data){
                    $.each($scope.rooms,function(){
                        this.roomStatus = $data.status;
                    });
                    sourcesInfoService.changeStatus($scope.rooms,$data.status,$scope);
                };

                $scope.hasCheckedRoom = function(){
                    var hasChecked = false;
                    $.each($scope.rooms,function(){
                        if(this.checked === true){
                            hasChecked = true;
                            return false;
                        }
                    });
                    return hasChecked;
                };

                //删除选中房间
                $scope.deleteRooms = function(){
                    if($scope.hasBindErp()){
                        return false;
                    }
                    if($scope.hasCheckedRoom()){
                        var title = $scope.bindZtc === true ? '请确保该房源在直销秒杀应用中没有设置秒杀房源，是否确认删除？':'确定删除选定房间吗？';
                        util.confirm(title, {
                            ok: function () {
                                sourcesInfoService.deleteRooms($scope);
                            }
                        });
                    }else{
                        util.notify('请先选择要删除的房间！');
                        return false;
                    }
                };

                $scope.beforeUpdateRoom = function($dialogScope){
                    $dialogScope.roomStatusList = $scope.roomStatusList;
                };
                $scope.showUpdateRoom = function($dialogScope,$dialog){
                    if($scope.hasBindErp()){
                        $($dialog.node).find('[i-id=ok]').attr('disabled','');

                        $($dialog.node).find('input').attr('disabled','');

                        $($dialog.node).find('[i=title]').text('修改房间（已绑定ERP项目，不能修改！）')
                    }
                };
                //修改房间
                $scope.editRoom = function($data){

                    sourcesInfoService.writeRoom($data,$scope);

                };

                $scope.beforeUploadRoom = function($dialog,$dialogScope,$data){
                    $dialogScope.uploadRoom = function(){
                        if($dialogScope.uploadStatusNotify && $dialogScope.uploadStatusNotify.status === 'added'){
                            $dialogScope.uploadModel.upload();
                        }else{
                            util.alert('请选择要导入的Excel文件！');
                        }
                    };

                    $dialogScope.$watch('uploadStatusNotify', function (newValue, oldValue) {
                        if(newValue !== oldValue){
                            if(newValue.status === 'added'){
                                $dialogScope.filenameWarp = newValue.filename;
                            }else if(newValue.status === 'uploading'){
                                ui.showSucTip(newValue.msg);
                            }else if(newValue.status === 'success'){
                                ui.showSucTip(newValue.msg);
                                $dialogScope.filenameWarp = '';
                                sourcesInfoService.getRoomTree($rootScope.curProjectId,$scope);
                                $scope.search();
                                $dialog.close();
                            }else if(newValue.status === 'error'){
                                $('#loading').remove();
                                util.alert(newValue.msg,{ok:function(){
                                    sourcesInfoService.getRoomTree($rootScope.curProjectId,$scope);
                                    $scope.search();
                                    $dialog.close();
                                }});
                                //ui.showErrTip(newValue.msg);
                                $dialogScope.filenameWarp = '';
                            }
                        }

                    });

                    if($scope.hasBindErp()){
                        return false;
                    }
                    $data.proj_id = $rootScope.curProjectId;
                };

                $scope.uploadRoom = function($dialog){
                    $($dialog.node).find('[i-id=cacel]').hide();
                };


                $scope.hasBindErp = function(showTip){
                    var bol = $scope.bindErp == 1;//0为未绑定，1为绑定
                    if(bol && showTip){
                        util.notify('已绑定ERP项目，不能修改！');
                        //ui.showSucTip('已绑定ERP项目，不能修改！');
                    }
                    return bol;
                };

                //下载模板
                $scope.downloadTemplate = function () {
                    var hasLd = false;
                    _.each(indexData,function(value){
                        if(value.isbld == 1){
                            hasLd = true;
                        }
                    });
                    if(hasLd){
                        location.href='/api/index.php?r=ydxs/s-room/download-template&proj_id='+$rootScope.curProjectId;
                    }else{
                        util.alert('请新增楼栋后再下载模板！');
                    }
                };


                $("#tree_table")
                    .tree({
                        dragAndDrop: false,
                        useContextMenu: false,
                        autoOpen: 1, //展开级别
                        //创建节点时
                        onCreateLi: function (node, $li) {
                            //isbld : 0为区域，1为楼栋，2为项目
                            var html = "<div style='position:relative;height:35px;margin-top: -35px;margin-left:46px;'><div style='left:0;display:none;width: auto !important;' class='jqtree-btn' data-unit-id='" + node.id + "'>"
                            //$li.find(".jqtree-element")
                            if(node.isbld == '2'){//项目
                                html += "<a  \
                                    ng-show='bindErp == 0&&canEdit==1' ui-dialog='新增区域' \
                                    ui-dialog-url='inc/dialog/add_area_loudong.html' \
                                    ui-dialog-cache='false' \
                                    ui-dialog-show='addAreaLoudong(\"区域\",$data)' \
                                    ui-dialog-ok='addArea(\"" + node.id + "\",$data,$dialog,$dialogScope)'\
                                 style='margin-left:5px;' data-trigger='popup'>新增区域</a>\
                                 <a  \
                                    ng-show='bindErp == 0&&canEdit==1' ui-dialog='新增楼栋' \
                                     ui-dialog-url='inc/dialog/add_area_loudong.html' \
                                    ui-dialog-cache='false' \
                                    ui-dialog-show='addAreaLoudong(\"楼栋\",$data)' \
                                    ui-dialog-ok='addLoudong(\"" + node.id + "\",$data,$dialog,$dialogScope)'\
                                 style='margin-left:5px;' data-trigger='popup'>新增楼栋</a>"
                            }else {
                                var dialogTitle = '';
                                if(node.isbld == '0'){//区域
                                    dialogTitle = '区域';
                                    html += " <a  \
                                    ng-show='bindErp == 0&&canEdit==1' ui-dialog='新增楼栋' \
                                    ui-dialog-url='inc/dialog/add_area_loudong.html' \
                                    ui-dialog-cache='false' \
                                    ui-dialog-show='addAreaLoudong(\"楼栋\",$data)' \
                                    ui-dialog-ok='addLoudong(\"" + node.id + "\",$data,$dialog,$dialogScope)'\
                                     style='margin-left:5px;' data-trigger='popup'>新增楼栋</a>";
                                }else{//楼栋
                                    dialogTitle = '楼栋';
                                }


                                html += "<a  \
                                        ng-show='bindErp == 0&&canEdit==1' ui-dialog='编辑"+dialogTitle+"' \
                                        ui-dialog-url='inc/dialog/add_area_loudong.html' \
                                        ui-dialog-cache='false' \
                                        ui-dialog-show='editAreaLoudong(\"" + node.name + "\",\"" + dialogTitle + "\",$data,$dialogScope)' \
                                        ui-dialog-ok='updateAreaLoudong(\"" + node.id + "\",$data,$dialog,$dialogScope)'\
                                     style='margin-left:5px;' data-trigger='popup'>编辑</a>\
                                    <a  ng-show='bindErp == 0' style='margin-left:5px;' data-trigger='dele'>删除</a>"
                            }
                            html += '</div></div>';
                            $li.find(".jqtree-element").append(html);

                            //title超过长度时，鼠标悬停应给出tip
                            var $title = $li.find('.jqtree-title');
                            $li.find(".jqtree-element").attr('title',$title.text());

                        },
                        onCanMove: function (node) {
                            return false;
                        },
                        onCanMoveTo: function (moved_node, target_node, position) {
                            return false;
                        },
                        onIsMoveHandle: function ($ele) {
                            return false;
                        },
                        onCanSelectNode: function (node) {
                            if (node.children.length == 0) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    })
                    .on('tree.select', function (e) {
                        var node = e.node;
                        if (node) {
                            //currentRole.set({
                            //    id: node.id,
                            //    name: node.name,
                            //    comments: node.comments
                            //});
                        }
                    })
                    .on('tree.click', function (e) {
                        var node = e.node;
                        var trigger = $(e.click_event.target).attr('data-trigger');
                        if (trigger) {
                            switch (trigger) {
                                case 'dele':
                                    e.preventDefault();

                                    var roleId = node.id;
                                    util.confirm('确定删除吗？', {

                                        ok: function () {
                                            sourcesInfoService.delBuilding(node.s_buildingId,$scope);
                                        }
                                    });
                                    break;
                                case 'popup':
                                    e.preventDefault();
                                    break;

                            }
                        }else{
                            $scope.query.s_buildingId = node.s_buildingId;

                            $scope.search();
                        }
                    })
                    .on("mouseenter",".jqtree-element",function(){
                            $(this).find(".jqtree-btn").show();
                    })
                    .on("mouseleave",".jqtree-element",function(){
                        $(this).find(".jqtree-btn").hide();
                    });

            }])
});